package ssi.staaar;

import ssi.staaar.control.StaaarControl;
import ssi.staaar.exceptions.ServerException;
import ssi.staar.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

public class RecoveryActivity extends Activity {
	private AlertDialog.Builder builderFields, builderServer;
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.recovery);
		builderFields = new AlertDialog.Builder(this);
		builderFields.setTitle(R.string.app_name)
		 	.setMessage(R.string.missing_fields)
		    .setNeutralButton("OK", new DialogInterface.OnClickListener() {
		        public void onClick(DialogInterface dialog, int id) {
		             dialog.dismiss();
		        }
		    });
	   builderServer = new AlertDialog.Builder(this);
	   builderServer.setTitle(R.string.app_name)
	    	.setMessage(R.string.server_unreachable)
		    .setNeutralButton("OK", new DialogInterface.OnClickListener() {
		        public void onClick(DialogInterface dialog, int id) {
		             dialog.dismiss();
		        }
		    });
	}
	
	public void sendRecoveryRequest(View v) {
		final EditText username = (EditText)findViewById(R.id.recUsernameEdit);
		final EditText password = (EditText)findViewById(R.id.recPwdEdit);
		if (username.getText().toString().equals("")) {
			AlertDialog missingFields = builderFields.create();
			missingFields.show();
		} else {
			StaaarControl stControl = new StaaarControl(
					getApplicationContext(),
					getString(R.string.serverAddress), 
					Integer.parseInt(getString(R.string.serverPort)),
					getString(R.string.keyPassword)
					);
			try {
				stControl.startConnection();
				boolean recovered = stControl.recoveryKey(username.getText().toString(), 
						password.getText().toString());
				if (recovered) {
					SharedPreferences settings = getSharedPreferences(Staaar.PREFS_NAME, 0);
					SharedPreferences.Editor editor = settings.edit();
					editor.putString("Username", username.getText().toString());
					editor.putBoolean("Registered", true);
					editor.commit();
					setResult(RESULT_OK);
					finish();
				} else {
					Log.d("REC/ACK", "recovered" + recovered);
					setResult(RESULT_CANCELED);
					finish();
				}
			} catch(ServerException e) {
				AlertDialog alertServer = builderServer.create();
				alertServer.show();
				e.printStackTrace();
			}
		}
	}
}
